using NalogGarLoader.Data;
using LinqToDB;
using LinqToDB.Data;
using LinqToDB.SchemaProvider;
using Microsoft.Identity.Client;
using NalogGarLoader.Data.Tables;

namespace NalogGarLoader.Model;

public class GarDbInitializator : IDisposable
{
    private static readonly NLog.Logger log = NLog.LogManager.GetCurrentClassLogger();

    public CleanupMode CleanupMode { get; set; } = CleanupMode.None;

    private GarDbContext GarDbContext { get; init; }
    public HashSet<string> TablesToImport {get ; set; }

    public GarDbInitializator(HashSet<string> tablesToImport, CleanupMode cleanupMode = CleanupMode.None) 
    {
        this.GarDbContext = new GarDbContext();
        this.TablesToImport = tablesToImport;
        this.CleanupMode = cleanupMode;
    }

    public void CleanupTable(string garTypeName)
    {
        if (this.CleanupMode == CleanupMode.None)
            return;        

        ITable<dynamic> table =  this.GarDbContext.GetTable(GarTypes.GarTypeMapping[garTypeName]);

        switch (CleanupMode)
        {
            case CleanupMode.Delete:
                log.Info($"Удаление данных из таблицы {garTypeName}");
                table.Delete();
                break;

            case CleanupMode.Truncate:
                log.Info($"Truncate таблицы {garTypeName}");

                table.Truncate();
                break;

            case CleanupMode.DropTable:
                log.Info($"Пересоздание таблицы {garTypeName}");
                table.Drop();
                this.CreateTable(garTypeName);
                break;
                
            default:
                throw new ArgumentException(nameof(CleanupMode));
        }            
    }

    public void CreateTable(string garTypeName)
    {
        Type entryType = GarTypes.GarTypeMapping[garTypeName];

        this.GarDbContext.CreateTable(tableType: entryType, tableOptions: TableOptions.CreateIfNotExists);      
    }

    private void InitBaseTables()
    {
        this.GarDbContext.CreateTable<ImportLog>(tableOptions: TableOptions.CreateIfNotExists);
        this.GarDbContext.CreateTable<CurrentVersion>(tableOptions: TableOptions.CreateIfNotExists);
    }    

    public void RunInit()
    {
        this.InitBaseTables();

        foreach (string garTypeName in this.TablesToImport)
        {
            this.CreateTable(garTypeName);
            this.CleanupTable(garTypeName);
        }
    }

    public void Dispose()
    {
        this.GarDbContext.Dispose();
    }    
}